<template>
  <section class="personal">
    <redPacketUtil v-if="redPacketBool" :anchorConfigObj="anchorConfig" @closePacketFn="closePacketFn"></redPacketUtil>
    <headerUtil :obj="headerObj" @closeFn="closeLivingFn">我的直播间</headerUtil>
    <div class="video-wrap">
      <div @click="initWebRTC(false)">主播端</div>
      <div @click="initWebRTC(true)">观众端</div>
      <video class="localVideoRef" ref="localVideoRef"  autoplay="autoplay"></video>
      <video ref="globalVideoRef"  autoplay="autoplay"></video>
    </div>
    <div :style="{display: canvasBool?'block':'none'}" class="svga-wrap" ref="svgaWrap"></div>
    <div class="content" @scroll.passive="scrollData" ref="scrollOut">
      <div class="item-wrap"  v-for="(item, index) in chatList" :key="index">
        <div :class="{'face-img':true, 'right-wrap':item.msg.userId == anchorConfig.userId, 'left-wrap':item.msg.userId != anchorConfig.userId}" :style="{background: `url(${item.msg.senderImg}) no-repeat center`}"></div>
        <div :class="{'content-wrap':true, 'right-wrap':item.msg.userId == anchorConfig.userId, 'left-wrap':item.msg.userId != anchorConfig.userId}">
          <div class="name">{{item.msg.senderName}}</div>
          <div class="text">{{item.msg.content}}</div>
          </div>
      </div>
    </div>
    <commonNavUtil 
    :livingType="1"
    :redPacketConfigCode="tempcode"
     @sendInfoFn="sendReview"
      @selectSvgaFn="sendGiftFn" 
      @startRedPacketFn="startRedPacketFn" 
      :anchorConfigObj="anchorConfig"></commonNavUtil>
  </section>
</template>
<script>
import reqApis from "../../req/reqApis.js";
import webrtcUtil from "../../req/wetrtcUtils.js";
import headerUtil from "../base/common/headerUtil.vue";
import redPacketUtil from "../base/common/redPacketUtil.vue";
import commonNavUtil from "../base/common/commonNavUtil.vue";

import SVGA from "svgaplayerweb";
// import Client from '../../req/common.js';


import {showToast} from 'vant';
export default {
  components: {
    headerUtil,
    commonNavUtil,
    redPacketUtil
  },
  data () {
    return {
      yourConn: null,
      PeerConnection: null,
      skillList: [],
      tempcode: null,
      redPacketBool: false,
      canvasBool: false,
      roomId: this.$route.query.roomId || 0,
      anchorConfig: {},

      user: {},
      websock: null,
      chatList: [],
      headerObj:{
        showType: 2,
        closeBtn: false
      },
      list: [],
      pageIndex: 1,
      isStop: false,
      canvas: {},
      player: {},
      parser: {}
    }
  },
  created() {

    if(this.roomId != null){
      reqApis.listSkuInfoApi({roomId: this.roomId}).then(res => {
        console.log(555, res.data)
        this.skillList = res.data;
      }).catch(err => {
        
      })
      reqApis.anchorConfigApi({roomId: this.roomId}).then(res => {
        this.anchorConfig = res.data;
        this.tempcode = this.anchorConfig.redPacketConfigCode;
        this.headerObj.closeBtn = this.anchorConfig.anchor;
        this.connectImServer();
      }).catch(err => {
        showToast(err.msg);
      })
    }
    
    // this.getUserFn();
  },
  mounted(){
    this.initSvga();
    
  },
  methods: {
    getUserFn(){
      reqApis.initPageApi({}).then(res => {
              this.user = res.data.userId;
            }).catch(err => {
                console.log(err)
            })
    },
    closePacketFn() {
        this.redPacketBool = false;
    },
  startRedPacketFn(){
    this.redPacketBool = true;
  },
  initSvga() {
    this.canvas = this.$refs.svgaWrap;
    this.player = new SVGA.Player(this.canvas);
    this.parser = new SVGA.Parser(this.canvas);
  },
  sendGiftFn(giftObj) {
    let params = {
        giftId: giftObj.id,
        roomId: this.roomId,
        receiverId: this.anchorConfig.anchorId,
        senderUserId: this.anchorConfig.userId,
        type: 0
      }; 
      reqApis.sendGiftApi(params).then(res => {
      }).catch(err => {
        showToast(err.msg);
      });
  },

  //渲染礼物特效svga
  playGiftSvga(url) {
      this.canvasBool = true;
      this.player.clearsAfterStop = true;
      this.player.stopAnimation();
      this.parser.load(url, (videoItem) => {
          this.player.loops = 1; // 设置循环播放次数是1
          this.player.setVideoItem(videoItem);
          this.player.startAnimation();
          this.player.onFinished(() => {
              console.log("动画停止了！！！");
              this.canvasBool = false;
          });
      });
      
      
  },
    connectImServer() {
      reqApis.getImConfigApi({}).then(res => {
        let url = `ws://${res.data.wsImServerAddress}/${res.data.token}/${this.anchorConfig.userId}/1001/${+this.roomId}`;
        // let url = "ws://192.168.2.166:9991/8d6b6c4f-1fb5-41bc-b0ff-77b258eb821d/100001/1001/"+this.roomId;
        console.log(url);
        this.websock = new WebSocket(url);
        this.websock.onmessage = this.websocketOnMessage;
        this.websock.onopen = this.websocketOnOpen;
        this.websock.onerror = this.websocketOnError;
        this.websock.onclose = this.websocketClose;
        console.log('初始化ws服务器');
        
      }).catch(err => {

      });
      // let url = "ws://"+that.imServerConfig.wsImServerAddress+"/" + that.imServerConfig.token+"/"+that.initInfo.userId+"/1001/"+this.roomId;
      
    },
    closeLivingFn() {
      reqApis.closeLivingApi({roomId: this.roomId}).then(res => {
        this.$router.push("/livingRoomList");
      }).catch(err => {
        


      })
    },
    scrollData() {
      let outH = this.$refs.scrollOut.scrollHeight,
          currentH = this.$refs.scrollOut.offsetHeight,
          offH = this.$refs.scrollOut.scrollTop;
        if(currentH + offH >= (outH-1)){
          this.pageIndex += 1;
        }
    },
     websocketOnOpen() {
        console.log('初始化连接建立');
    },

    websocketOnError() {
        console.error('出现异常');
    },
    websocketClose(e) {  //关闭
        console.log('断开连接', e);
    },
     websocketSend(data) {//数据发送
        this.websock.send(data);
    },
    startHeartBeatJob() {
        console.log('首次登录成功');
        //发送一个心跳包给到服务端
        let jsonStr = {"userId": this.anchorConfig.userId, "appId": 10001};
        let bodyStr = JSON.stringify(jsonStr);
        let heartBeatJsonStr = {"magic": 19231, "code": 1004, "len": bodyStr.length, "body": bodyStr};
        setInterval(() => {
            this.websocketSend(JSON.stringify(heartBeatJsonStr));
        }, 3000);

        if(this.anchorConfig.userId == this.anchorConfig.anchorId) {
          this.initWebRTC(false);
        }else{
          this.initWebRTC(true);
        }
    },
   

    websocketOnMessage(e) { //数据接收
        let wsData = JSON.parse(e.data);
        if(wsData.code == 1001) {
            this.startHeartBeatJob();
        } else if (wsData.code == 1003) {
            // let respData = JSON.parse(Client.utf8ByteToUnicodeStr());
          let respData = JSON.parse(wsData.bodyStr);
            //属于直播间内的聊天消息
            if(respData.bizCode==5555) {
                let respMsg = JSON.parse(respData.data);
                let sendMsg = {"userId": respMsg.userId, "content": respMsg.content, "senderName": respMsg.senderName, "senderImg": respMsg.senderAvtar};
                let msgWrapper = {"msgType": 1, "msg": sendMsg};
                this.chatList.push(msgWrapper);
                //注意让滑轮滚到底
                // this.$nextTick(() => {
                //     var div = document.getElementById('talk-content-box')
                //     div.scrollTop = div.scrollHeight
                // })
                //发送ack确认消息
            } else if(respData.bizCode == 5556) {
                //送礼成功
                let respMsg = JSON.parse(respData.data);

                // 默认值
                if(respMsg.giftId == 1){
                  this.playGiftSvga(new URL("../../assets/svga/爱心.svga", import.meta.url));
                }else if(respMsg.giftId == 2) {
                  this.playGiftSvga(new URL("../../assets/svga/女巫.svga", import.meta.url));
                }else if(respMsg.giftId == 3) {
                  this.playGiftSvga(new URL("../../assets/svga/跑车.svga", import.meta.url));
                }else if(respMsg.giftId == 4) {
                  this.playGiftSvga(new URL("../../assets/svga/头像.svga", import.meta.url));
                }
            } else if(respData.bizCode == 5557){
                //送礼失败
                let respMsg = JSON.parse(respData.data);
                this.$message.error(respMsg.msg);
            } else if (respData.bizCode == 5560) {
                if(!this.startingRedPacket) {
                    this.startingRedPacket=true;
                    //开始红包雨活动
                    let respMsg = JSON.parse(respData.data);
                    let redPacketConfig = JSON.parse(respMsg.redPacketConfig);
                    initRedPacket(redPacketConfig.totalCount,redPacketConfig.configCode);
                }
                
            ///判断是否为推送过来的信令	candidate : 6001	
            }else if (respData.bizCode == 6001) {
              if(this.anchorConfig.userId != this.anchorConfig.anchorId){
              }
              setTimeout(() => {
                console.log("被叫方初始化webRtc完毕--->");
              console.log("被叫方初始化webRtc完毕--this.yourConn->", this.yourConn);
              }, 3000);
              
              let respMsg = JSON.parse(respData.data);
              let content = JSON.parse(respMsg.content);
              //设置信令的应答
              console.log("this.yourConn--》", this.yourConn);
              console.log("message.content--》", content);
              
              console.log("message.content-candidate-》", content.candidate);
              //处理ICE备选
              this.yourConn.addIceCandidate(new RTCIceCandidate(content));
              
            }else if (respData.bizCode == 6002) {
              console.log("offer22");
              setTimeout(() => {
                console.log("offer22完毕--this.yourConn->", this.yourConn);
              }, 3000);
              // 观众端，接受主播传递的offer
              this.handleOffer(respData);


            }else if (respData.bizCode == 6003) {
              console.log("answer111");
              setTimeout(() => {
              console.log("answer111完毕--this.yourConn->", this.yourConn);
              }, 3000);
              // 主播端，接受观众端传递的answer
              this.handleAnswer(respData);
            }else if(respData.bizCode == 6004) {
              console.log("主播6004")
              this.initWebRTC(false);
            }

            this.sendAckCode(respData);
        }
    },
    sendAckCode(respData) {
        let jsonStr = {"userId": this.anchorConfig.userId, "appId": 10001,"msgId":respData.msgId};
        let bodyStr = JSON.stringify(jsonStr);
        let ackMsgStr = {"magic": 19231, "code": 1005, "len": bodyStr.length, "body": bodyStr};
        this.websocketSend(JSON.stringify(ackMsgStr));
    },
    sendReview(info){
        if (info == '') {
          showToast("评论不能为空");
            return;
        }
        let sendMsg = {"userId":this.anchorConfig.userId, "content": info, "senderName": this.anchorConfig.watcherNickName, "senderImg": this.anchorConfig.watcherAvatar};
        let msgWrapper = {"msgType": 1, "msg": sendMsg};
        this.chatList.push(msgWrapper);
        //发送评论消息给到im服务器
        let msgBody = {"roomId":this.roomId,"type":1,"content":info,  "senderName": this.anchorConfig.watcherNickName, "senderAvtar": this.anchorConfig.watcherAvatar};
        let jsonStr = {"userId": this.anchorConfig.userId, "appId": 10001,"bizCode":5555,"data":JSON.stringify(msgBody)};
        let bodyStr = JSON.stringify(jsonStr);
        console.log('发送消息');
        let reviewMsg = {"magic": 19231, "code": 1003, "len": bodyStr.length, "body": bodyStr};
        console.log(JSON.stringify(reviewMsg));
        this.websocketSend(JSON.stringify(reviewMsg));
    
    },
    
			//获取摄像头权限失败时执行的回调
			errorFunc(err) {
				console.log("主叫方获取摄像头权限失败--->", err);
				if ("NotFoundError" == err.name) {
					alert("设备不具备视频、音频条件或没有音视频权限");
				} else {

					alert(err.name);
				}

			},
      initoffer() {
        this.yourConn.createOffer(offer =>  {
            // 发送评论消息给到im服务器
            let msgBody = {"roomId":this.roomId,"type":1,"content": offer,  "senderName": this.anchorConfig.watcherNickName, "senderAvtar": this.anchorConfig.watcherAvatar};
            let jsonStr = {"userId": this.anchorConfig.userId, "appId": 10001,"bizCode":6002,"data":JSON.stringify(msgBody)};
            let bodyStr = JSON.stringify(jsonStr);
            // console.log('发送消息');
            let reviewMsg = {"magic": 19231, "code": 1003, "len": bodyStr.length, "body": bodyStr};
            // console.log(JSON.stringify(reviewMsg));
            this.websocketSend(JSON.stringify(reviewMsg));
            //将这个 SDP offer 设置为本地端的会话描述
						this.yourConn.setLocalDescription(offer);
          }, function(error) {
						console.log("Error when creating an offer");
					});
        
      },
    initWebRTC(watchBool) {
      this.yourConn = null;
      this.PeerConnection = null;
      console.log(this.yourConn)
      // if (this.yourConn != null && !watchBool) {
      //   return;
      // }


      this.yourConn = webrtcUtil.initPeerConnection(this.PeerConnection, this.$refs.globalVideoRef);
      console.log("initPeerConnection ", this.PeerConnection)
      console.log("yourConn ", this.yourConn)
        // 在发现新的 ICE 候选时执行的回调
				this.yourConn.onicecandidate = (event) => {
          
          //是否存在 ICE 候选
          if (event.candidate) {
            //如果存在 ICE 候选，则通过 WebSocket 发送 ICE 候选信息给对端
            console.log("发送ICE候选--->" );
            //发送评论消息给到im服务器
            let msgBody = {"roomId":this.roomId,"type":1,"content":event.candidate,  "senderName": this.anchorConfig.watcherNickName, "senderAvtar": this.anchorConfig.watcherAvatar};
            let jsonStr = {"userId": this.anchorConfig.userId, "appId": 10001,"bizCode":6001,"data":JSON.stringify(msgBody)};
            let bodyStr = JSON.stringify(jsonStr);
            console.log('发送消息');
            let reviewMsg = {"magic": 19231, "code": 1003, "len": bodyStr.length, "body": bodyStr};
            console.log(JSON.stringify(reviewMsg));
            this.websocketSend(JSON.stringify(reviewMsg));

          }

        }
        
        if(watchBool){

          // 当signalingState变为stable时，表示初始化已完成
                let msgBody = {"roomId":this.roomId,"type":1,"content": "",  "senderName": this.anchorConfig.watcherNickName, "senderAvtar": this.anchorConfig.watcherAvatar};
                let jsonStr = {"userId": this.anchorConfig.userId, "appId": 10001,"bizCode":6004,"data":JSON.stringify(msgBody)};
                let bodyStr = JSON.stringify(jsonStr);
                console.log('发送消息qqqqqqq');
                let reviewMsg = {"magic": 19231, "code": 1003, "len": bodyStr.length, "body": bodyStr};
                console.log(JSON.stringify(reviewMsg));
                this.websocketSend(JSON.stringify(reviewMsg));
            return;
          }



      webrtcUtil.initUserMedia(
        (err) => {
          console.log("主叫方获取摄像头权限失败--->", err);
        },
        (myStream) => {
          console.log("摄像头权限获取成功--->", myStream);
             //播放本地摄像头捕捉到的画面
            this.$refs.localVideoRef.srcObject = myStream;
          // 添加流到对等连接，这里stream 是本地摄像头或麦克风捕获的音视频流，使用 addStream 方法将这个流添加到对等连接中，以便与远程对等连接共享
            this.yourConn.addStream(myStream);

          console.log("发送offer--->");
          this.yourConn.createOffer(offer =>  {
            // 发送评论消息给到im服务器
            let msgBody = {"roomId":this.roomId,"type":1,"content": offer,  "senderName": this.anchorConfig.watcherNickName, "senderAvtar": this.anchorConfig.watcherAvatar};
            let jsonStr = {"userId": this.anchorConfig.userId, "appId": 10001,"bizCode":6002,"data":JSON.stringify(msgBody)};
            let bodyStr = JSON.stringify(jsonStr);
            // console.log('发送消息');
            let reviewMsg = {"magic": 19231, "code": 1003, "len": bodyStr.length, "body": bodyStr};
            // console.log(JSON.stringify(reviewMsg));
            this.websocketSend(JSON.stringify(reviewMsg));
            //将这个 SDP offer 设置为本地端的会话描述
						this.yourConn.setLocalDescription(offer);
          }, function(error) {
						console.log("Error when creating an offer");
					});
        }
      )

    },
    handleOffer(respData){
      let respMsg = JSON.parse(respData.data);
      let content = JSON.parse(respMsg.content);
      console.log("被叫方接受到offer--- this.yourConn 》", this.yourConn);
      console.log("被叫方接受到data----- data-- 》", respMsg);
      console.log("data.content------ 》", content);
      console.log("data.content.sdp------ 》", content.sdp);
      this.yourConn.setRemoteDescription(new RTCSessionDescription(content));


      this.yourConn.createAnswer(answer => {
        console.log("createAnswer111", answer)
        this.yourConn.setLocalDescription(answer);
        console.log("createAnswer222")

        //发送评论消息给到im服务器
        let msgBody = {"roomId":this.roomId,"type":1,"content": answer,  "senderName": this.anchorConfig.watcherNickName, "senderAvtar": this.anchorConfig.watcherAvatar};
        let jsonStr = {"userId": this.anchorConfig.userId, "appId": 10001,"bizCode":6003,"data":JSON.stringify(msgBody)};
        let bodyStr = JSON.stringify(jsonStr);
        console.log('发送消息6003');
        let reviewMsg = {"magic": 19231, "code": 1003, "len": bodyStr.length, "body": bodyStr};
        console.log("创建应答数据",JSON.stringify(reviewMsg));
        this.websocketSend(JSON.stringify(reviewMsg));
        console.log(1111222222)
      },error => {
					console.log("Error when creating an answer");
			});

    },
    handleAnswer(respData){
      let respMsg = JSON.parse(respData.data);
      let content = JSON.parse(respMsg.content);
      console.log("主叫方接受到应答----- this.yourConn-- 》", this.yourConn);
      console.log("data.content------ 》", content);
				console.log("主叫方接受到应答----- data-- 》", respMsg);
				this.yourConn.setRemoteDescription(new RTCSessionDescription(content));
    },

  },

  
  
}
</script>
<style lang="less" scoped>
.personal {
  width: 3.75rem;
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
  .video-wrap {
    width: 3.75rem;
    height:2.5rem;
    background: red;
    .localVideoRef {
      width: 3.75rem;
      height:2.5rem;
    }
  }
  .content {
    flex: 1;
    overflow-y: auto;
    .list {
      background: white;
      overflow: hidden;
    }
    .item-wrap {
      width: 3.75rem;
      min-height: 0.5rem;
      margin: .1rem 0;
      .face-img {
        width: 0.5rem;
        height: 0.5rem;
        background-size: contain !important;
      }
    }
    .left-wrap {
      float: left;
      .text {
        background: white;
      }
    }
    .right-wrap {
      float: right;
      text-align: right;
      .text {
        background: #9adc9a;
      }
    }
    .content-wrap {
      display: inline-block;
      min-height: 0.5rem;
      max-width: 3.2rem;
      padding: 0.05rem;
      .name {
        font-size: 0.12rem;
        padding:.02rem;
      }
      .text {
        display: inline-block;
        word-wrap: break-word;
        font-size: 0.16rem;
        line-height: 0.2rem;
        padding: 0.05rem;
        border-radius: 0.04rem;
      }
    }
  }
  .svga-wrap {
    z-index: 999;
    position: absolute;
    top:  -10%;
    height: 70%;
    width: 100%;
  }
}
</style>

